package com.csu.analysis.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.csu.analysis.service.XiaoMiService;
import com.csu.device.dao.BehaviorDao;
import com.csu.device.entity.Behavior;
import com.csu.device.entity.Device;
import com.csu.device.service.HardWareService;
import com.csu.push.WebSocketPush;
import com.csu.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 环境监测设备
 */
@Service
public class XiaoMiServiceImpl implements XiaoMiService {

    @Autowired
    private HardWareService hardWareService;

    @Autowired
    private BehaviorDao behaviorDao;

    @Override
    public void todoDeviceByXiaoMi(JSONObject jsonObject, String deviceSn) throws Exception {
        Device device = (Device) RedisUtil.get(deviceSn);
        if (null == device) {
            return;
        }
        String deviceData = jsonObject.getString("deviceData");
        Integer gatewayType = device.getDeviceType();//获取设备类型1:门磁；2:TOF；3:人体红外；4:椅垫；5:温湿度；6:火焰；7:水浸；8:血压计；9:体温；10:床垫；11:GPS 12:烟感 13无线开关 14 ，报警 15签到 16 体征监测 17托管 18用餐 19震动帖20开卡',
        JSONObject tokey = new JSONObject();
        tokey.put("deviceSn", deviceSn);
        String swit = "";

        //温湿度传感器
        if (7 == gatewayType) {
            String[] datas = deviceData.split(",");
            Double t = Double.parseDouble(datas[0].split("=")[1]) / 100;
            if (t > 38 || t < 5) {
                jsonObject.put("message", deviceSn + ":温度异常:" + t);
                //烟雾报警
                hardWareService.callPolice(2, "温度异常:" + t, device, 1);
            }else{
                tokey.put("data", deviceData);
                this.saveTf(device,t);
            }

        }

        //烟感传感器
        if (8 == gatewayType) {
            String[] datas = deviceData.split("=");
            if ("Yes".equals(datas[1])) {
                swit = "on";
                //烟雾报警
                hardWareService.callPolice(2, "烟雾报警", device, 1);

            } else {
                swit = "off";
            }
            tokey.put("data", swit);
            //设备使用分析
            this.onAndOff(device, swit);
        }

        //水浸
        if (10 == gatewayType) {
            String[] datas = deviceData.split("=");
            if ("Yes".equals(datas[1])) {
                swit = "on";
            } else if ("No".equals(datas[1])) {
                swit = "off";
            }
            tokey.put("data", swit);
            //设备使用分析
            this.onAndOff(device, swit);
        }

        //门磁
        if (14 == gatewayType) {
            String[] datas = deviceData.split("=");
            if ("1".equals(datas[1])) {
                swit = "on";
            } else if ("0".equals(datas[1])) {
                swit = "off";
            }
            tokey.put("data", swit);
            //设备使用分析
            this.onAndOff(device, swit);
        }

        //人体红外
        if (12 == gatewayType) {
            String[] datas = deviceData.split("=");
            if ("1".equals(datas[1])) {
                swit = "on";
            } else if ("0".equals(datas[1])) {
                swit = "off";
            }
            tokey.put("data", swit);
            //设备使用分析
            this.saveTof(device, swit);
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        tokey.put("time", simpleDateFormat.format(new Date()));
        WebSocketPush.xiaoMiPush(tokey, device.getDeviceRelas(), deviceSn,device.getDeviceType());

        //全体群推送
        WebSocketPush.sendAllMessage(jsonObject, deviceSn);
    }

    /**
     * 保存温湿度
     * @param device
     * @param tf
     */
    private void saveTf(Device device, Double tf) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Behavior behavior = hardWareService.getDevRelaToDo(device.getDeviceRelas(), device.getDeviceSn());
        behavior.setRemark(simpleDateFormat.format(new Date()) + ":当前温度:"+tf+"℃");
        behavior.setStartTime(new Date());
        behavior.setBehaviorType(1);
        behavior.setAnomalies(0);
        behaviorDao.addBehavior(behavior);
    }


    private void saveTof(Device device, String swit) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Behavior behavior = hardWareService.getDevRelaToDo(device.getDeviceRelas(), device.getDeviceSn());
        behavior.setRemark(simpleDateFormat.format(new Date()) + ":有人经过。");
        behavior.setStartTime(new Date());
        behavior.setBehaviorType(1);
        behavior.setAnomalies(0);
        behaviorDao.addBehavior(behavior);
    }

    private void onAndOff(Device device, String swit) {
        Behavior behavior;
        if (null == device.getBehavior()) {
            behavior = hardWareService.getDevRelaToDo(device.getDeviceRelas(), device.getDeviceSn());
            if (swit.equals("on")) {
                behavior.setStartTime(new Date());
            }

            //缓存数据
            device.setBehavior(behavior);
           // RedisUtil.del(device.getDeviceSn());
            RedisUtil.set(device.getDeviceSn(), device);
        } else {
            if (swit.equals("off")) {
                behavior = device.getBehavior();
                behavior.setEndTime(new Date());

                if (null != behavior.getStartTime()) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

                    Double distanceTime = this.getDistanceTime2(behavior.getStartTime(), behavior.getEndTime());
                    if (distanceTime > 1.0) {
                        behavior.setRemark("开启: " + simpleDateFormat.format(behavior.getStartTime()) + " 关闭: " + simpleDateFormat.format(behavior.getEndTime()) + "时长(秒): " + distanceTime);
                        behavior.setBehaviorType(1);
                        behavior.setAnomalies(0);
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("starttime", this.getTimeByV(behavior.getStartTime()));
                        jsonObject.put("duration", distanceTime);
                        behavior.setDataValue(jsonObject.toJSONString());
                        behaviorDao.addBehavior(behavior);
                    } else {
                        //重置使用
                        device.setBehavior(null);
                      //  RedisUtil.del(device.getDeviceSn());
                        RedisUtil.set(device.getDeviceSn(), device);
                    }

                }
                //重置使用
                device.setBehavior(null);
               // RedisUtil.del(device.getDeviceSn());
                RedisUtil.set(device.getDeviceSn(), device);
            }

        }
    }


    private String getTimeByV(Date startTime) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return simpleDateFormat.format(startTime);
    }

    //计算时间差，以小时为单位。如：2018-08-08 和 2018-08-07 相差24h
    public double getDistanceTime2(Date startTime, Date endTime) {
        double hour = 0;
        long time1 = startTime.getTime();
        long time2 = new Date().getTime();

        long diff;
        if (time1 < time2) {
            diff = time2 - time1;
        } else {
            diff = time1 - time2;
        }
        return diff / 1000;
    }

}
